from volcenginesdkarkruntime import Ark
import os

# 初始化Volcengine Ark客户端
client = Ark(
    api_key="780242c1-b80a-43d1-b5a1-fcc5bea20248",
    # base_url="https://ark.cn-beijing.volces.com/api/v3"
)

def get_user_file_path():
    """获取用户输入的文件路径"""
    while True:
        file_path = input("请输入要转换的Vue文件路径（输入q退出）: ").strip()

        if file_path.lower() == 'q':
            print("已退出程序")
            return None

        if not os.path.exists(file_path):
            print(f"错误：文件 '{file_path}' 不存在，请重新输入")
            continue

        if not file_path.endswith('.vue'):
            print(f"警告：文件 '{file_path}' 不是.vue文件，是否继续？(y/n)")
            confirm = input().strip().lower()
            if confirm != 'y':
                continue

        return file_path

def read_file_content(file_path):
    """读取文件内容"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except Exception as e:
        print(f"读取文件失败: {e}")
        return None

def generate_vue_component(prompt):
    response = client.chat.completions.create(
        model="deepseek-r1-250120",
        messages=[
            {"role": "system", "content": """你是一个专业的前端架构师，请将以下AngularJS代码转换为Vue2格式，
            
            1、其中遇到$http时使用fetch替换,
            2、注意：当遇到
            dialogService.sidebar("uc.demensionGet", {
                bodyClose: false,
                width: '50%',
                pageParam: { code: code, title: '查看维度', action: action }
            });
            或者：
            dialogService.page("approvalManager.approval.showDiff", {
              area: ["65vw", "95vh"],
              btn: [],
              title: "查看差异",
              pageParam: {
                toApprove: true,
                differFrequency: $scope.differFrequency,
                differWorkOrder: $scope.differWorkOrder,
                tempScope: $scope
              }
            })
            
            我们把它改造成组件引入进来，要在vue中的components中注册这个组件，如下所示 ：
            import demensionGetDlg from './dlg/demensionGetDlg'

            components: {
                demensionGetDlg: demensionGetDlg
              },
            <demensionGetDlg ref="demensionGetDlg" width="400px" @onSuccess="$refs.htTable.load();"></dlg>
            
            然后，我们在js中这样做：
            this.$refs.demensionGetDlg.open({ code: code, title: '查看维度', action: action })
            或者：
            this.$refs.demensionGetDlg.open({
                toApprove: true,
                differFrequency: $scope.differFrequency,
                differWorkOrder: $scope.differWorkOrder,
                tempScope: $scope
              })
            3、其中遇到baseService时使用request替换,
            这样引入进来：import request from '@/utils/request',
            当baseService的url中,如："${portal}/sys/sysType/v1/getTypesByTypeKeyAndGroupKey?typeKey=engineering_classification&groupKey=RESOURCE_TYPE"
            当遇到${xxx}时转换成${context.xxx}，并且用模板字符串``包起来，转换后是：
            `${context.portal}/sys/sysType/v1/getTypesByTypeKeyAndGroupKey?typeKey=engineering_classification&groupKey=RESOURCE_TYPE`
            
            注意：request.get是get，request.post是post，注意转换
            
            还有，如果是带参数，如：?parentId="+$scope.dataEdit.parentId+"&isRoot="+$scope.dataEdit.isRoot+"&isPriNode="+$scope.dataEdit.isPriNode，
            那么request.post()/request.get()也按照这样带参，不能转换成json形式传参
            
            4、其中遇到$sessionStorage时使用sessionStorage替换
            
            
            5、如果页面中class有col-md-2相关的，可以转换成el-row和el-column
            
            6、当遇到：ht-table时，使用ht-table中ht-table来替换，
             ht-query时，使用ht-table中ht-table-search-panel来替换，并且如下引入：
             import OrgTree from '@/components/orgTree/OrgTree'

             
             7、当遇到ht-org-tree-select时，使用orgTree来替换，如下模板所示：
             
             当遇到ht-query的select时，如：
             <select id="resourceLocationType" class="form-control input-sm"
                    ng-model="resourceLocationType" ht-query="resource_location_type" operation="equal"
                    ng-options="calendar.key as calendar.name for calendar in wzlx">
                <option value="">请选择</option>
            </select>
            
            我们改造成如下这样的代码：
            <ht-table-search-field
              label="动力类型"
              ref="powerTypeRef"
              prop="macPowerType"
              operation="EQUAL"
              type="select"
              :props="{ key: 'key', value: 'name' }"
            />
            并且这样赋值：
            this.$refs.powerTypeRef.changeOptions(this.powerType)
            
            8、当遇到
                  <label class="col-md-1 control-label">创建时间</label>
                    <div class="col-md-3">
                        <input type="datetime" time-type-start ht-date="yyyy-MM-dd HH:mm:ss" class="form-control" type="text"
                               style="display: inline-block;width: 45%;float: left;" ht-query="row_time"
                               ng-model="createStartDate" operation="great_equal"/>
                        <input class="form-control" type="text" value="~"
                               style="width: 10%;display: inline-block;float: left;padding: 0;border: none;background: #fff;text-align: center;"
                               readonly/>
                        <input type="datetime" time-type-end ht-date="yyyy-MM-dd HH:mm:ss" class="form-control" type="text" operation="less_equal"
                               style="display: inline-block;width: 45%;float: right;" ht-query="row_time"
                               ng-model="createEndDate"/>
                    </div>
                    改成
            <ht-table-search-field
              label="创建时间"
              prop="row_time"
              type="daterange"
            />
            9、当遇到
               <button type="button" class="btn btn-sm btn-info"
                            ng-click="enable()" ht-method-auth="enable_environmental_gardening">
                         启用
                    </button>
                    <button type="button" class="btn btn-sm btn-info"
                            ng-click="disable()" ht-method-auth="disable_environmental_gardening">
                         停用
                    </button>
            改成
                <el-button type="info" size="small" @click="enable">启用</el-button>
            <el-button type="info" size="small" @click="disable">停用</el-button>   
            enable写成一个方法，把id传进去，写一个弹窗
            this.$alert('确定启用', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            
          }
        });
        
        10、当遇到<ht-table>的时候必须要有@load="loadData"方法，请参考下面这个例子
         <ht-table @load="loadData"
              :data="data"
              :pageResult="pageResult"
              :show-export="false"
              :show-custom-column="true"
              :selectable="false"
              :isLoadTable="false"
              :advanceReset="resetFilter"
              :justShowSearch="true"
              ref="htTable">
               loadData (param, cb) {
      let querys = param.querys || []
      this.$handleOrgQuery(param, null, 'orgId')
      console.log('---------')
      console.log(this.currentName)

      console.log('---------')
      // param = JSON.parse(JSON.stringify(param).replace('orgId', 'u.org_Id'))
      if (this.userName) {
        // user_Name
        param.querys.push({ group: 'advance', operation: 'LIKE', property: 'u.user_name', relation: 'AND', value: this.userName })
      }

      // param.querys = querys

      this.$http.post('${plusOperation}/attendanceGroup/v1/queryList', param)
        .then(
          resp => {
            let response = resp.data
            if (response) {
              this.data = response.rows
              if (this.data != undefined) {
                this.data.forEach(ele => {
                  this.maxCount = this.maxCount + ele.countUser
                })
              }
              this.pageResult = {
                page: response.page,
                pageSize: response.pageSize,
                total: response.total
              }
              cb()
            }
          })
        .finally(() => cb())
    },
        
            注意：用户输入的angularjs中的html代码按照我下面的模板代码转换成vue2
            
            <template>
              <div class="fullheight">
                <ht-table
                  @load="loadData"
                  :data="data"
                  :pageResult="pageResult"
                  :selection="true"
                  quick-search-props="projectSystemCode"
                  :show-export="false"
                  :show-custom-column="true"
                  @selection-change="handleSelectionChange"
                  ref="htTable">
                  <template v-slot:toolbar>
                    <el-button-group>
                      <el-button type="primary" size="small" @click="showDialog('add')" icon="el-icon-plus">添加</el-button>
                      <el-button type="danger" size="small" @click="showDeleteDlg()" icon="el-icon-plus">删除</el-button>
                      <el-button size="small" @click="exportFile()" icon="el-icon-download">导出</el-button>
                    </el-button-group>
                  </template>
                  <template v-slot:search>
                    <ht-table-search-panel :label-width="120" :divide="3">
                      <ht-table-search-field
                        label="所属组织"
                        prop="org"
                        operation="EQUAL"
                        type="custom"
                        clearable
                        ref="custom_org">
                        <template #custom>
                          <orgTree v-model="queryOrg"></orgTree>
                        </template>
                      </ht-table-search-field>
                      <ht-table-search-field
                        label="楼栋"
                        ref="buildingCode"
                        prop="buildingCode"
                        operation="EQUAL"
                        type="select"
                        :props="{ key: 'buildingCode', value: 'buildingName' }"
                      />

                      <ht-table-search-field label="楼栋名称" prop="buildingName" operation="LIKE"/>
                      <ht-table-search-field
                        label="是否启用"
                        prop="enabledFlag"
                        operation="EQUAL"
                        type="select"
                        :options="[{key:'0', value: '否'},{key: 1, value: '是'}]"
                      />
                    </ht-table-search-panel>
                  </template>
                  <template>
                    <ht-table-column type="index" width="50" align="center" label="序号"/>
                    <ht-table-column prop="divideName" label="所属组织" :show-overflow-tooltip="true"></ht-table-column>
                    <ht-table-column
                      prop="buildingCode"
                      label="楼栋编码"
                      :show-overflow-tooltip="true"
                    ></ht-table-column>
                    <ht-table-column
                      prop="buildingName"
                      label="楼栋名称"
                      :show-overflow-tooltip="true"
                    ></ht-table-column>
                    <ht-table-column
                      prop="buildingInnerName"
                      label="楼栋别名"
                      :show-overflow-tooltip="true"
                    ></ht-table-column>
                    <ht-table-column
                      prop="floorCount"
                      label="楼栋层数"
                      :show-overflow-tooltip="true"
                    ></ht-table-column>
                    <ht-table-column
                      prop="enabledFlagName"
                      label="状态"
                      :show-overflow-tooltip="true"
                      width="130"
                    ></ht-table-column>
                    <ht-table-column
                      prop="workRoleName"
                      label="操作"
                      :show-overflow-tooltip="true"
                      width="220">
                      <template v-slot="{ row }">
                        <el-button @click="showDialog('edit', row.id)" type="success" plain>修改</el-button>
                        <el-button type="success" @click="showDialog('view', row.id)" plain>查看</el-button>
                        <el-button :type="row.enabledFlag == 1 ?'danger':'success'" plain @click="disEnable(row.id, row.enabledFlag)">
                          {{ row.enabledFlag == 1 ? '禁用' : '启用' }}
                        </el-button>
                      </template>
                    </ht-table-column>
                  </template>
                </ht-table>
                <dlg ref="dlg" width="40%" @onSuccess="$refs.htTable.load();"></dlg>
              </div>
            </template>
            <script>
            import OrgTree from '@/components/orgTree/OrgTree'
            import dlg from './dlg'
            export default {
              name: 'projectSystemInfoManager',
              components: {
                orgTree: OrgTree,
                dlg
              },
              data () {
                return {
                  buildingList: [],
                  resourceTypeTree: [],
                  queryOrg: [],
                  queryRes: [],
                  orgTreeData: [],
                  removeIds: [],
                  dialogVisible: false,
                  data: [],
                  pageResult: {
                    page: 1,
                    pageSize: 50,
                    total: 0
                  },
                  ProjectSystemInfo: {},
                  saveMethod: 'POST',
                  lines: [],
                  // 作业角色列表
                  workRoleList: [],
                  // 事项分类列表
                  matterTypeList: []
                }
              },
              methods: {
                changeBuilding () {
                },
                disEnable (id, type) {
                  this.$confirm(`您确定要${type == 1 ? '禁用' : '启用'}?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {

                  })
                },
                // 导出文件
                async exportFile () {
                  let params = this.$refs.htTable.getParams()
                  let res = await mdmApi.exportFile(params)
                  // console.log("res=");
                  let blob = new Blob([res.data], {
                    type:
                      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
                  })
                  let link = document.createElement('a')
                  document.body.appendChild(link)
                  link.href = window.URL.createObjectURL(blob)
                  // 配置下载的文件名
                  link.download = '楼栋信息'
                  link.click()
                },
                handleSelectionChange (rows) {
                  console.log('---rows---', rows)
                  this.removeIds = []
                  rows.forEach(row => {
                    if (row.id) {
                      this.removeIds.push(row.id)
                    }
                  })
                },
                showDeleteDlg () {
                  if (this.removeIds.length == 0) {
                    return this.$message('请先选择数据')
                  }
                  this.$confirm('确定删除该数据？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  })
                    .then(async () => {
                    })
                    .catch((e) => {
                      console.log('e=', e)
                      this.$message({
                        type: 'info',
                        message: '删除报错'
                      })
                    })
                },
                showDialog (action, id) {
                  this.$validator.reset() // 重置校验
                  if (id) {
                  } else {
                    this.$refs.dlg.open(action)
                  }
                },
                loadData (param, cb) {
                  this.$handleOrgQuery(param)
                  param = JSON.parse(JSON.stringify(param).replace('orgId', 'divideId'))
                  this.$http
                    .post('${mdm}/api/mdm/v1/building/list', param)
                    .then(
                      resp => {
                        console.log('--- loadData ---', resp)
                        let response = resp.data
                        if (response) {
                          cb()
                          this.data = response.rows
                          this.pageResult = {
                            page: response.page,
                            pageSize: response.pageSize,
                            total: response.total
                          }
                        }
                      },
                      error => {
                        reject(error)
                      }
                    )
                    .finally(() => cb())
                }
              }
            }
            </script>

            <style lang="scss" scoped>

            </style>

            只输出转换后完整的代码，不要任何解释和说明"""},
            {"role": "user", "content": prompt}
        ],
        stream=True
    )

    full_content = []
    for chunk in response:
        if chunk.choices:
            content = chunk.choices[0].delta.content
            if content:
                full_content.append(content)

    return "".join(full_content)

def save_converted_code(file_path, vue_code):
    """保存转换后的代码"""
    while True:
        choice = input("请选择保存方式:\n1. 覆盖原文件\n2. 另存为新文件\n3. 不保存\n选择: ").strip()

        if choice == '1':
            # 覆盖原文件
            try:
                with open(file_path, 'w', encoding='utf-8') as file:
                    file.write(vue_code)
                print(f"已成功覆盖原文件: {file_path}")
                return
            except Exception as e:
                print(f"保存文件失败: {e}")
                return

        elif choice == '2':
            # 另存为新文件
            new_path = input("请输入新文件路径: ").strip()
            if not new_path:
                print("无效路径")
                continue

            try:
                # 确保目录存在
                os.makedirs(os.path.dirname(new_path), exist_ok=True)
                with open(new_path, 'w', encoding='utf-8') as file:
                    file.write(vue_code)
                print(f"已成功保存到新文件: {new_path}")
                return
            except Exception as e:
                print(f"保存文件失败: {e}")
                return

        elif choice == '3':
            print("未保存转换结果")
            return

        else:
            print("无效选择，请重新输入")

def main():
    print("Vue文件转换工具")
    print("=" * 30)

    while True:
        # 获取用户输入的文件路径
        file_path = get_user_file_path()
        if not file_path:
            break

        print(f"您选择的文件: {file_path}")

        # 读取文件内容
        angularjs_code = read_file_content(file_path)
        if not angularjs_code:
            continue

        print(f"成功读取文件内容（{len(angularjs_code)} 字符）")

        # 调用转换函数
        vue_code = generate_vue_component(angularjs_code)

        if vue_code:
            print("\n转换后的List Vue代码：\n")
            print(vue_code[:500] + "..." if len(vue_code) > 500 else vue_code)  # 只显示前500字符

            # 询问用户是否保存
            save_choice = input("\n是否保存转换结果？(y/n): ").strip().lower()
            if save_choice == 'y':
                save_converted_code(file_path, vue_code)

        # 询问是否继续转换其他文件
        continue_choice = input("\n是否继续转换其他文件？(y/n): ").strip().lower()
        if continue_choice != 'y':
            print("感谢使用，再见！")
            break

if __name__ == "__main__":
    main()
